package com.hzcx.app.simplechat.view;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import com.hzcx.app.simplechat.R;

/**
 * 发送验证码文本
 */
public class SendCodeTextView extends AppCompatTextView {

    private Context context;
    private CountDownTimer countDownTimer;

    public SendCodeTextView(Context context) {
        super(context);
        init(context);
    }

    public SendCodeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SendCodeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        setText("发送验证码");
        setTextColor(context.getResources().getColor(R.color.color_282F3E));
    }

    /**
     * 开始计时
     */
    public void start() {
        //倒计时
        countDownTimer = new CountDownTimer(60000 + 1050, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                sendIng(millisUntilFinished);
            }

            @Override
            public void onFinish() {
                sendFinish();
            }
        }.start();
    }

    /**
     * 正在发送验证码
     *
     * @param millisUntilFinished
     */
    private void sendIng(long millisUntilFinished) {
        setEnabled(false);
        setTextColor(context.getResources().getColor(R.color.color_A5A7AF));
        if (millisUntilFinished > 1000) {
            setText("重新获取(" + (millisUntilFinished / 1000 - 1) + "s)");
        }
    }

    /**
     * 发送完毕，可以重新发送
     */
    private void sendFinish() {
        setEnabled(true);
        setTextColor(context.getResources().getColor(R.color.color_272F3D));
        setText("重新获取");
    }

    /**
     * 停止发送
     */
    public void stopSend() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        sendFinish();
    }
}
